package com.obrempon.credit.market.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.Gravity
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.obrempon.credit.market.R
import com.obrempon.credit.market.common.CommonActivity
import com.obrempon.credit.market.configs.ObremponApiPath
import com.obrempon.credit.market.configs.ObremponApiUrl
import com.obrempon.credit.market.configs.ObremponApiUrl.addCommonParams
import com.obrempon.credit.market.configs.ObremponConfigs
import com.obrempon.credit.market.databinding.ObremponPermissionsActBinding
import com.obrempon.credit.market.event.ObremponEventData
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.request.IHttpCallback
import com.obrempon.credit.market.ui.adapter.ObremponPermissionApt
import com.obrempon.credit.market.ui.dialog.ObremponPermissionReasonDialog
import com.obrempon.credit.market.ui.dialog.ObremponTipsDialog
import com.obrempon.credit.market.utils.ObremponTitleBarUtil
import com.obrempon.credit.market.utils.helper.ObremponConfigsHelper
import com.obrempon.credit.market.utils.helper.ObremponProcessHelper
import com.obrempon.credit.market.utils.log.ObremponLogger
import com.obrempon.credit.market.utils.shared.ObremponSharedHelper
import com.obrempon.credit.market.utils.shared.ObremponSharedKey
import com.obrempon.module.adapter.ObremponOnItemChildClickListener
import com.obrempon.module.shapeview.drawable.ShapeGradientOrientation
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions
import java.math.BigDecimal
import java.math.RoundingMode

/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/28 14:04
 * @Annotation：权限
 */
class ObremponPermissionsAct: CommonActivity(),EasyPermissions.RationaleCallbacks {
    lateinit var binding: ObremponPermissionsActBinding

    private val PERMISSION_REQUEST_CODE : Int = 100;
    private var selectedIndex = -1
    private var permissionAdapter: ObremponPermissionApt? = null

    companion object {
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        private const val INTENT_KEY_AMOUNT = "amount"
        private const val INTENT_KEY_UNIT = "unit"
        fun start(context: Context, pName: String, pToken: String,amount: String,unit: String) {
            val intent = Intent(context, ObremponPermissionsAct::class.java)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            intent.putExtra(INTENT_KEY_AMOUNT, amount)
            intent.putExtra(INTENT_KEY_UNIT,unit)
            context.startActivity(intent)
        }
    }

    override fun takeObremponRootView(): View {
        binding = ObremponPermissionsActBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initObremponView() {
        ObremponTitleBarUtil.setStatusBarLightMode(this, true)
        setObremponTitleBarVisibility(View.VISIBLE)
        rootViewBinding.rootLayout.shapeDrawableBuilder
            .setSolidGradientColors(getColor(R.color.color_ffcbe0ff),getColor(R.color.white),getColor(R.color.white))
            .setSolidGradientOrientation(ShapeGradientOrientation.TOP_TO_BOTTOM)
            .intoBackground()
        setObremponTextTitle(getString(R.string.obrempon_permission_title))
        initObremponPermissionListView()
        binding.permissionContentLayout.visibility = View.INVISIBLE
    }

    override fun initObremponListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Permission Page")
        }
        //填写进件信息 || 申贷
        binding.buttonInformation.setOnClickListener {
            //上报 HARDWARE、STORE、DEVICE
            publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_SYC_STORE_DEVICE_HARDWARE))
            publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_SYC_AL_MS))
            //进件信息未完成
            if (ObremponProcessHelper.takeObremponAuthStepList().size > 0){
                //进入进件信息
                ObremponAuthStepsAct.start(this,takeObremponIntentProductAmount())
                finish()
            } else {
                val token = takeObremponIntentProductToken()
                if (token.isEmpty()){
                    onObremponCopyProductToChildProductAction(takeObremponIntentProductName())
                } else {
                    //进入申贷
                    ObremponApplyAct.start(this,takeObremponIntentProductName(),takeObremponIntentProductToken())
                    finish()
                }
            }
        }
    }

    override fun takeObremponData() {
        val showKey = getString(R.string.obrempon_permission_tips_key)
        val showText = String.format(getString(R.string.obrempon_permission_tips),showKey)
        val startIndex = showText.indexOf(showKey)
        val tipsSpannable = SpannableString(showText)
        tipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.color_ffff7226)), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        tipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textPermissionTips.text = tipsSpannable

        //进件信息是否完成
        if (ObremponProcessHelper.takeObremponAuthStepList().size > 0){
            binding.buttonInformation.text = getString(R.string.obrempon_permission_complete_information)
        } else {
            binding.buttonInformation.text = getString(R.string.obrempon_button_apply)
        }
        takeObremponPermissionDataList()
    }

    /**
     * 初始化权限列表
     */
    private fun initObremponPermissionListView(){
        binding.permissionListView.setHasFixedSize(true)
        binding.permissionListView.isNestedScrollingEnabled = false
        binding.permissionListView.isFocusableInTouchMode = false //不需要焦点
        binding.permissionListView.layoutManager = LinearLayoutManager(this)
        permissionAdapter = ObremponPermissionApt(binding.permissionListView)
        binding.permissionListView.adapter = permissionAdapter
        binding.permissionListView.itemAnimator = DefaultItemAnimator()
        permissionAdapter?.setOnItemChildClickListener(ObremponOnItemChildClickListener { _, childView, position ->
            val item = permissionAdapter?.getItem(position) ?: return@ObremponOnItemChildClickListener
            selectedIndex = position
            showObremponPermissionReasonDialog()
//            showObremponRequestPermissionTipsDialog()
        })
    }

    /**
     * 显示额度
     */
    @SuppressLint("SetTextI18n")
    private fun showObremponMaxAmount(){
        //显示额度 = 额度 / 2
        var showAmount = BigDecimal(takeObremponIntentProductAmount()).divide(BigDecimal("2"),2, RoundingMode.UP).stripTrailingZeros().toPlainString()
        var showPassRate = "0"
        if (permissionAdapter != null){
            for (i in 0..< permissionAdapter!!.itemCount){
                val item = permissionAdapter!!.getItem(i)
                if (item.optBoolean("isSystem") && !item.optBoolean("isAgree")){
                    continue
                }
                if (!item.optBoolean("isSystem") && !item.optBoolean("isRead")){
                    continue
                }
                showAmount = BigDecimal(showAmount).add(BigDecimal(item.optString("creditLine"))).stripTrailingZeros().toPlainString()
                showPassRate = BigDecimal(showPassRate).add(BigDecimal(item.optString("passRate"))).stripTrailingZeros().toPlainString()
            }
        }
        binding.textAmount.text = "${takeObremponIntentUnit()} $showAmount"
        binding.textPassRate.text = "$showPassRate%"
    }

    /**
     * 显示是否存在被拒绝的权限
     */
    private fun showObremponFailureView(){
        var isShowFailure = false
        if (permissionAdapter != null) {
            for (i in 0..<permissionAdapter!!.itemCount) {
                val item = permissionAdapter!!.getItem(i)
                if (item.optBoolean("isSystem") && item.optBoolean("disagree")){
                    isShowFailure = true
                    break
                }
            }
        }
        if (isShowFailure){
            binding.permissionTipsLayout.visibility = View.GONE
            binding.failureLayout.visibility = View.VISIBLE
        } else {
            binding.permissionTipsLayout.visibility = View.VISIBLE
            binding.failureLayout.visibility = View.GONE
        }
    }

    /**
     * 用户点击同意授权后会回调该方法
     */
    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        ObremponLogger.e("Permission page onPermissionsGranted, code: $requestCode , permissions : $perms")
        if (requestCode == PERMISSION_REQUEST_CODE && selectedIndex != -1){
            val item = permissionAdapter?.getItem(selectedIndex)
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_PERMISSION_SYSTEM_AGREE,item?.optString("permission"))
        }
        takeObremponPermissionDataList()
    }

    /**
     * 用户点击拒绝授权后会回调该方法
     */
    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        ObremponLogger.e("onPermissionsDenied code: $requestCode , permissions : $perms")
        if (requestCode == PERMISSION_REQUEST_CODE && selectedIndex != -1){
            val item = permissionAdapter?.getItem(selectedIndex)
            item?.put("isAgree",false)
            item?.put("disagree",true)
            permissionAdapter?.notifyItemChanged(selectedIndex)
            checkObremponCompleteIsEnabled()
            showObremponFailureView()

            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_PERMISSION_SYSTEM_DENY, item?.optString("permission"))
        }

        // 如果申请的权限中有任何一个权限存在 永久拒绝 的情况
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            // 设置 引导用户前往设置界面 自行设置权限的引导对话框
            AppSettingsDialog.Builder(this)
//                .setTitle("需要手动设置权限")
//                .setRationale("存在永久拒绝的权限 , 需要手动前往设置界面为应用进行授权")
//                .setPositiveButton("前往设置界面")
//                .setNegativeButton("不使用该功能")
                .build().show()
        }
    }

    override fun onRationaleAccepted(requestCode: Int) {
        ObremponLogger.e("onRationaleAccepted, code: $requestCode")
    }

    override fun onRationaleDenied(requestCode: Int) {
        ObremponLogger.e("onRationaleDenied, code: $requestCode")
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE && selectedIndex != -1){
            val item = permissionAdapter?.getItem(selectedIndex)
            // 判断权限是否申请成功
            val hasPermissions = EasyPermissions.hasPermissions(this, item?.optString("permission"))
            if (hasPermissions){
                takeObremponPermissionDataList()
            }
            // 界面中显示权限申请结果
//            showObremponToast("设置界面用户手动申请权限结果 $hasPermissions")
        }
    }

    /**
     * 加载权限列表
     */
    private fun takeObremponPermissionDataList(){
        //显示额度 = 额度 / 2
        val showAmount = BigDecimal(takeObremponIntentProductAmount()).divide(BigDecimal("2"),2, RoundingMode.UP).stripTrailingZeros().toPlainString()
        val permissionList = ObremponConfigsHelper.takeObremponPermissionsList()
        permissionList.add(getString(R.string.obrempon_permission_applist))
        val list = arrayListOf<JSONObject>()
        for (i in 0..< permissionList.size){
            val item = JSONObject()
            val permission = permissionList[i]
            item.put("permission",permission)
            when(permission){
                "android.permission.READ_SMS" -> {
                    item.put("title",getString(R.string.obrempon_permission_sms))
                    item.put("titleReason",getString(R.string.obrempon_permission_sms_data_collection))
                    item.put("icon",R.mipmap.obrempon_permission_msg_icon)
                    item.put("iconReason",R.mipmap.obrempon_permission_msg_white_icon)
                    item.put("reason",getString(R.string.obrempon_permission_sms_reason))
                    item.put("requestReason",getString(R.string.obrempon_permission_sms_request_reason))
                    item.put("passRate","40")
                    item.put("creditLine", BigDecimal(showAmount).multiply(BigDecimal("0.4")).stripTrailingZeros().toPlainString())
                    item.put("isSystem",true)
                    item.put("isAgree",EasyPermissions.hasPermissions(this,permission))
                }
                "android.permission.READ_PHONE_STATE" -> {
                    item.put("title",getString(R.string.obrempon_permission_phone_status))
                    item.put("titleReason",getString(R.string.obrempon_permission_phone_status_data_collection))
                    item.put("icon",R.mipmap.obrempon_permission_phone_state_icon)
                    item.put("iconReason",R.mipmap.obrempon_permission_phone_state_white_icon)
                    item.put("reason",getString(R.string.obrempon_permission_phone_status_reason))
                    item.put("requestReason",getString(R.string.obrempon_permission_phone_status_request_reason))
                    item.put("passRate","30")
                    item.put("creditLine", BigDecimal(showAmount).multiply(BigDecimal("0.3")).stripTrailingZeros().toPlainString())
                    item.put("isSystem",true)
                    item.put("isAgree",EasyPermissions.hasPermissions(this,permission))
                }
                else -> {
                    item.put("title",permission)
                    item.put("titleReason",getString(R.string.obrempon_permission_applist_data_collection))
                    item.put("icon",R.mipmap.obrempon_permission_applist_icon)
                    item.put("iconReason",R.mipmap.obrempon_permission_applist_white_icon)
                    item.put("reason",getString(R.string.obrempon_permission_applist_reason))
                    item.put("requestReason",getString(R.string.obrempon_permission_applist_request_reason))
                    item.put("passRate","20")
                    item.put("creditLine", BigDecimal(showAmount).multiply(BigDecimal("0.2")).stripTrailingZeros().toPlainString())
                    item.put("isSystem",false)
                    item.put("isRead",ObremponSharedHelper.queryObremponSharedBoolean(ObremponSharedKey.OBREMPON_ALLIST_READ))
                }
            }
            list.add(item)
        }
        launch(Dispatchers.Main){
            delay(200)
            permissionAdapter?.data = list
            showObremponMaxAmount()
            showObremponFailureView()
            binding.permissionContentLayout.visibility = View.VISIBLE
            checkObremponCompleteIsEnabled()
        }
    }

    /**
     * 获取产品名称
     */
    private fun takeObremponIntentProductName(): String{
        return intent.extras?.getString(INTENT_KEY_PRODUCT,"").toString()
    }

    /**
     * 获取产品Token
     */
    private fun takeObremponIntentProductToken(): String{
        return intent.extras?.getString(INTENT_KEY_TOKEN,"").toString()
    }

    /**
     * 获取产品额度
     */
    private fun takeObremponIntentProductAmount(): String{
        return intent.extras?.getString(INTENT_KEY_AMOUNT,"").toString()
    }

    /**
     * 获取单位
     */
    private fun takeObremponIntentUnit(): String{
        return intent.extras?.getString(INTENT_KEY_UNIT,"").toString()
    }

    /**
     * 提示dialog
     */
    private fun showObremponRequestPermissionTipsDialog(){
        val item = permissionAdapter?.getItem(selectedIndex) ?: return
        val requestPermission = item.optString("permission")
        val dialog = ObremponTipsDialog(this,requestPermission, object : ObremponTipsDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view?.id){
                    R.id.buttonConfirm -> {
                        showObremponPermissionReasonDialog()
                    }
                    R.id.buttonCancel -> {
                        addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_PERMISSION_REASON_DIALOG_DENY,requestPermission)
                    }
                }
            }
        })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        dialog.setObremponKindTipsIconResource(R.mipmap.obrempon_dialog_kind_tips_icon)
        dialog.setObremponKindTipsTitleText(getString(R.string.obrempon_dialog_kind_tips_title),getColor(R.color.black))
        dialog.setObremponKindTipsMsgText(getString(R.string.obrempon_permission_dialog_agree_tips))
        dialog.setObremponKindTipsMsgGravity(Gravity.CENTER)
        dialog.isObremponKindTipsDoubleButton(true)
        dialog.setObremponKindTipsButtonCancelText(getString(R.string.obrempon_button_cancel))
        dialog.setObremponKindTipsButtonCancelBackgroundResource(getColor(R.color.color_fff6f6f6))
        dialog.setObremponKintTipsButtonConfirmText(getString(R.string.obrempon_button_ok))
        dialog.setObremponKindTipsButtonConfirmBackgroundResource(getColor(R.color.color_ff0066ff))
    }

    /**
     * 显示权限描述文案
     */
    private fun showObremponPermissionReasonDialog(){
        val item = permissionAdapter?.getItem(selectedIndex) ?: return
        val requestPermission = item.optString("permission")
        val dialog = ObremponPermissionReasonDialog(this,requestPermission,object : ObremponPermissionReasonDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view?.id){
                    R.id.buttonAgree -> {
                        when(item.optBoolean("isSystem")){
                            true -> {//系统权限
                                EasyPermissions.requestPermissions(this@ObremponPermissionsAct, item.optString("requestReason"),PERMISSION_REQUEST_CODE,requestPermission)
                            }
                            else -> {//非系统权限
                                ObremponSharedHelper.addObremponSharedData(ObremponSharedKey.OBREMPON_ALLIST_READ,true)
                                //重新加载权限列表数据
                                takeObremponPermissionDataList()
                            }
                        }
                        addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_PERMISSION_REASON_DIALOG_AGREE,requestPermission)
                    }
                    R.id.buttonDeny -> {
                        addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_PERMISSION_REASON_DIALOG_DENY,requestPermission)
                    }
                }
            }
        })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        dialog.setObremponPermissionReason(item)
    }

    /**
     * 检查确认按钮是否可点击
     */
    private fun checkObremponCompleteIsEnabled(){
        var isEnabled = true
        for (i in 0..< permissionAdapter!!.itemCount){
            val item = permissionAdapter?.getItem(i) ?: break
            when(item.optBoolean("isSystem")){
                true -> {//系统权限
                    if (!item.optBoolean("isAgree")){
                        isEnabled = false
                        break
                    }
                }
                else -> {
                    if (!item.optBoolean("isRead")){
                        isEnabled = false
                        break
                    }
                }
            }
        }
        binding.buttonInformation.isEnabled = isEnabled
    }

    /**
     * 复制主产品信息到目标产品
     */
    private fun onObremponCopyProductToChildProductAction(targetProduct: String){
        showObremponLoading()
        val params = JSONObject()
            .addCommonParams()
            .apply {
                put("path", ObremponApiPath.OBREMPON_PATH.OBREMPON_API_LOAN_PRODUCT_COPY_PATH)
                put("sourceProduct", ObremponConfigs.OBREMPON_APPNAME)
                put("targetProduct",targetProduct)
            }
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hideObremponLoading()
                val obj = data.optJSONObject("obj")
                var pToken = ""
                if (obj != null){
                    pToken = obj.optString("token","")
                    ObremponApplyAct.start(this@ObremponPermissionsAct,takeObremponIntentProductName(),pToken)
                }
                finish()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_PERMISSION_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_PERMISSION_END)
    }
}